package com.ruoyi.party.system.validate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * //获取默认提示信息 String defaultConstraintMessageTemplate =
 * context.getDefaultConstraintMessageTemplate(); System.out.println("default
 * message :" + defaultConstraintMessageTemplate); //禁用默认提示信息
 * context.disableDefaultConstraintViolation(); //设置提示语
 * context.buildConstraintViolationWithTemplate("can not contains
 * blank").addConstraintViolation(); return false;
 * 
 * @author 黄宝康
 *
 */
public class TimeRangekValidator implements ConstraintValidator<TimeRange, String> {

	@Override
	public void initialize(TimeRange constraintAnnotation) {

	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		// 对时间字符串进行比较
		String pattern = "[0-2]\\d:[0-5]\\d:[0-5]\\d-[0-2]\\d:[0-5]\\d:[0-5]\\d";

		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(value);
		if (m.matches()) {
			// 时间格式符合的情况下，验证前者时间小于后者时间
			String[] arr = value.split("-");
			String begin = arr[0];
			String end = arr[1];
			String[] begin_arr = begin.split(":");
			String begin_hour = begin_arr[0];
			String begin_minute = begin_arr[1];
			String begin_second = begin_arr[2];

			String[] end_arr = end.split(":");
			String end_hour = end_arr[0];
			String end_minute = end_arr[1];
			String end_second = end_arr[2];

			if (Integer.parseInt(begin_hour) <= Integer.parseInt(end_hour)) {
				if (Integer.parseInt(begin_hour) == Integer.parseInt(end_hour)) {
					// 小时相等的情况下才需要比较分钟
					if (Integer.parseInt(begin_minute) <= Integer.parseInt(end_minute)) {
						if (Integer.parseInt(begin_minute) == Integer.parseInt(end_minute)) {
							// 分钟相等的情况下才需要比较秒
							if (Integer.parseInt(begin_second) < Integer.parseInt(end_second)) {
								return true;
							} else {
								// 设置提示语
								context.buildConstraintViolationWithTemplate("起止时间区间-秒验证失败").addConstraintViolation();
								return false;
							}
						} else {
							return true;
						}
					} else {
						// 设置提示语
						context.buildConstraintViolationWithTemplate("起止时间区间-分钟验证失败").addConstraintViolation();
						return false;
					}
				} else {
					return true;
				}
			} else {
				// 设置提示语
				context.buildConstraintViolationWithTemplate("起止时间区间-小时验证失败").addConstraintViolation();
				return false;
			}
		} else {
			// 设置提示语
			context.buildConstraintViolationWithTemplate("起止时间区间-格式不正确").addConstraintViolation();
			return false;
		}
	}
}